<?php

namespace app\admin\controller\app;

use app\common\controller\Backend;
use app\common\model\app\Topic as TopicModel;
use app\common\model\app\TopicData as TopicDataModel;
use app\common\model\app\TopicTwodays as TopicTwodaysModel;
use app\common\model\app\Intel as IntelModel;
use app\common\model\app\IntelComment as IntelCommentModel;
// use think\Cache;

/**
 * 话题管理
 *
 * @icon fa fa-circle-o
 */
class Topic extends Backend
{

    /**
     * Topic模型对象
     * @var \app\common\model\app\Topic
     */
    protected $model = null;

    protected $redis = null;

    public function _initialize()
    {
        parent::_initialize();
        // 实例化Redis
        $this->redis = new \fast\cache\driver\Redis([
            'prefix'     => 'gfw_'
        ]);
        $this->model = new \app\common\model\app\Topic;
        $this->view->assign("hotswitchList", $this->model->getHotswitchList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model

                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model

                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','name','countisr','countpv','countshare','countpraise','countcomment','twodayspv','twodaysshare','twodayspraise','twodayscomment','hotswitch','createtime']);

            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 刷新数据
     * @return array 成功|失败
     */
    public function refreshdata()
    {
        // 任务
        // 数据清理：
        // 1、每天03:00，清理15天前情报量为0的话题。
        // 2、每天03:00，清理15天前的统计数据
        // 数据统计：
        // 1、系统每2小时统计并记录话题相关数据，包括关联情报总数、总访问量、总转发数、评论数、总点赞数 完成
        // 2、48小时新增数=当前计算总量-48小时前计算总量
        if( $this->request->isAjax() ){
            // 获取总数据
            // $list = $this->getTopicCountData();
            // 更新一次总数据进话题表
            // $topicModel = model('app.Topic');
            // $topicModel->isUpdate()->saveAll($list);
            // 48小时就更新一次
            // $this->twodaysUpdate();

            // 使用缓存后更新方法
            $topics = $this->redis->get('topic');
            // return $topics;
            if( $topics != '' ){
                foreach ($topics as $k => $v) {
                    // return $v;
                    // 根据缓存化的话题统计 同写入数据表更新数据表的统计
                    TopicModel::where('name', $k)->update($v);
                }
            }

            $this->success('操作成功');
        }
    }

    /**
     * 统计一次话题总数据
     * 多久一次按任务计划时间就行 2小时一次
     * @return array json 成功更新后的数据集
     */
    public function twohoursCountTopic()
    {
        // 获取总数据
        $list = $this->getTopicCountData();
        // 更新一次总数据进话题表
        $topicModel = model('app.Topic');
        $topicModel->isUpdate()->saveAll($list);
        // 48小时就更新一次
        $this->twodaysUpdate();
        // 转为对应的数据表字段
        $t = [];
        foreach ($list as $k => $v) {
            $t[$k]['topic_id'] = $v['id'];
            $t[$k]['twohoursisr'] = $v['countisr'];
            $t[$k]['twohourspv'] = $v['countpv'];
            $t[$k]['twohoursshare'] = $v['countshare'];
            $t[$k]['twohourspraise'] = $v['countpraise'];
            $t[$k]['twohourscomment'] = $v['countcomment'];
        }
        // 保存数据进话题数据表
        $topicDataModel = model('app.TopicData');
        $result = $topicDataModel->allowField(true)->saveAll($t);
        // 返回新增话题数据 json格式
        // return json_encode([
        //     'msg'  => 'ok',
        //     'code' => '200',
        //     'data' => $result
        // ]);
        $this->success('操作成功', $result);
    }

    /**
     * 获取话题总数据 [总情报数，总访问量，总分享数，总点赞数，总评论数]
     * @package IntelModel
     * @package IntelCommentModel
     * @return array
     */
    public function getTopicCountData()
    {
        $list = $this->model->where('countisr' > 0)->select();
        $c = [];
        foreach ($list as $k => $v) {
            // 获取情报话题总数
            $countisr = IntelModel::where('topic_ids', 'like', '%' . $v['id'] . '%')->count();
            // 返回数据出来格式
            $c['count'][$v['name']] = [
                'id'           => $v['id'],
                'countisr'     => $countisr,
                'countpv'      => 0,
                'countshare'   => 0,
                'countpraise'  => 0,
                'countcomment' => 0
            ];
            $intelArr = IntelModel::where('topic_ids', 'like', '%' . $v['id'] . '%')->field(['id','pvnum','sharenum','praisenum'])->select();
            foreach ($intelArr as $key => $value) {
                // 获取评论总数
                $commentArr = IntelCommentModel::where('intel_id',$value['id'])->count();
                $c['count'][$v['name']]['countcomment'] += $commentArr;
                $c['count'][$v['name']]['countpv'] += $value['pvnum'];
                $c['count'][$v['name']]['countshare'] += $value['sharenum'];
                $c['count'][$v['name']]['countpraise'] += $value['praisenum'];
            }
        }
        return $c['count'];
    }

    /**
     * 更新话题表的48小时的数据
     * @return [type] [description]
     */
    public function twodaysUpdate()
    {
        // 48小时新增数=当前计算总量-48小时前计算总量
        $t = time();
        $list = TopicModel::field('name,topiclead,addpv,addshare,addpraise,hotswitch,updatetime',true)->select();
        // 设置Unix时间戳 要大于多少开始执行 2天
        $unixValue = 172800;
        foreach ($list as $k => $v) {
            $maxTime = TopicTwodaysModel::where('topic_id',$v['id'])->max('twodaystime');
            $res = TopicDataModel::where('topic_id',$v['id'])->select();
            if( $v['twodaystime'] == NULL ) {
                if( ($t - $v['createtime']) > $unixValue ){
                    TopicModel::update([
                        'id'             => $v['id'],
                        'twodayspv'      => $v['countpv'],
                        'twodaysshare'   => $v['countshare'],
                        'twodayspraise'  => $v['countpraise'],
                        'twodayscomment' => $v['countcomment'],
                        'twodaystime'    => $t
                    ]);
                    // 写入48小时记录表
                    TopicTwodaysModel::create([
                        'topic_id'       => $v['id'],
                        'twodayspv'      => $v['countpv'],
                        'twodaysshare'   => $v['countshare'],
                        'twodayspraise'  => $v['countpraise'],
                        'twodayscomment' => $v['countcomment'],
                        'twodaystime'    => $t
                    ]);
                }
            }elseif( ($t - $maxTime) > $unixValue ){
                $twodaysList = TopicTwodaysModel::where('topic_id',$v['id'])->select();
                $newTwodaysData = [
                    'id'             => $v['id'],
                    'topic_id'       => $v['id'],
                    'twodayspv'      => $v['countpv'],
                    'twodaysshare'   => $v['countshare'],
                    'twodayspraise'  => $v['countpraise'],
                    'twodayscomment' => $v['countcomment'],
                    'twodaystime'    => $t
                ];
                foreach ($twodaysList as $k1 => $v1) {
                    $newTwodaysData['twodayspv'] -= $v1['twodayspv'];
                    // $this->success($newTwodaysData['twodayspv']);
                    // return $newTwodaysData['twodayspv'];
                    $newTwodaysData['twodaysshare'] -= $v1['twodaysshare'];
                    $newTwodaysData['twodayspraise'] -= $v1['twodayspraise'];
                    $newTwodaysData['twodayscomment'] -= $v1['twodayscomment'];
                }
                // 写入48小时记录表 这个ID字段
                model('app.TopicTwodays')->isUpdate(false)->allowField(true)->save($newTwodaysData);
                // 写入话题表
                model('app.Topic')->isUpdate(true)->allowField(true)->save($newTwodaysData);
            }
        }
    }

    public function redis()
    {
        // $this->redis->rm('topic');
        $time = time();
        $d = date('Y-m-d H:i:s', $time);

        $t = $this->redis->get('topic');
        if( !is_array($t) ){
            die('你还没有将话题初始化过哦！');
        }
        $topicName = '#topic4#';
        $topicData = [
            'createtime' => $time,
            'countpv'    => 654,
            'countisr'   => 797,
            'countcomment' => 43
        ];

        // $g = array_key_exists($topicName, $g);

        // 判断话题名缓存是否存在
        if(array_key_exists($topicName, $t)) {
            $oldData = $t[$topicName];
            $newData[$topicName] = array_merge($oldData,$topicData);
            $g = array_merge($t, $newData);
        } else {
            $g = array_merge($t, [$topicName => $topicData]);
        }

        $this->redis->set('topic',$g);
        $g = $this->redis->get('topic');
        // $g = $this->redis->get('__menu__');
        // $this->redis->clear();

        // halt($oldData);
        halt($g);
    }

    public function test()
    {
        $list = [
            'b' => true,
            'a' => false,
            'c' => false
        ];
        // halt($this->redis->get('topic'));
        // $i = 0;
        // $data = [];
        // foreach ($list as $k => $v) {
        //     if( !$v ) {
        //         switch ($k)
        //         {
        //             case "a":
        //             $data = 123;
        //             break;
        //             case "b":
        //             $data = 456;
        //             break;
        //             case "c":
        //             $data = 789;
        //             break;
        //             default:
        //             $data = 'init';
        //         }
        //         break;
        //     }
        // }
        // halt($data);
        // $arr = [
        //     ''
        // ];
        // $rand = mt_rand(0, count($arr)-1);
        // $rand = mt_rand(0, count($arr)-1);
        // $params = '{"Content":"'.base64_encode($arr[$rand]).'"}';
        // $params = '{"Content":"'.base64_encode($arr[$rand]).'"}';
        $content = '屌你老妈草泥马去你吗的死B。全家死光光，特朗普就是个垃圾冰粉，K粉，摇头丸';
        $content = '#今日关注##今日关注##今日关注##&<<>>&&&#你服从<调配我草你>>嘛屌??死你';
        $params = '{"Content":"'.base64_encode($content).'"}';
        $res = \think\Hook::listen('text_moderation', $params);
        halt($res);
        if ($res[0]['Data']['EvilFlag'] > 0 || $res[0]['Data']['EvilType'] > 100) {
            $detailResult = $res[0]['Data']['DetailResult'];
            $data = '';
            foreach ($detailResult as $k => $v) {
                // $preposition . $typeText . '；' . '标签：' . $label . '；' . '分值：' . $score;
                switch ($v['EvilType'])
                {
                    case "20001":
                        $evilType = '政治';
                    break;
                    case "20002":
                        $evilType = '色情';
                    break;
                    case "20006":
                        $evilType = '涉毒违法';
                    break;
                    case "20007":
                        $evilType = '谩骂';
                    break;
                    case "20105":
                        $evilType = '广告引流';
                    break;
                    case "24001":
                        $evilType = '暴恐';
                    break;
                    default:
                        $data = '文本审核不通过';
                }
                $keywords = $v['Keywords'];
                if( $v['Keywords'] !== '' ){
                    $keywordsCount = count($keywords);
                    $keyword = '';
                    for ($i=0; $i <= ($keywordsCount-1); $i++) {
                        if($keywordsCount > 1){
                            if( ($keywordsCount-1) == $i){
                                $keyword .= $keywords[$i];
                            }else{
                                $keyword .= $keywords[$i] . '、';
                            }
                        }else{
                            $keyword .= $keywords[$i];
                        }
                    }
                }else{
                    $keywords = '';
                }
                $data .= '文本审核不通过，恶意类型：' . $evilType . '，关键字：' . $keyword . '，分值：' . $v['Score'] . '；';
            }
        }
        halt($data);
        // $params = '{"FileUrl":"http://images.china.cn/attachement/jpg/site1000/20160712/7427ea2109f818eea0f31b.jpg"}';
        $params = '{"FileUrl":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595416831328&di=7867e965ccfb73edeec56bd008dca9b0&imgtype=0&src=http%3A%2F%2Fimg.mp.sohu.com%2Fupload%2F20170519%2F0e235c170038463f9cbb6884d11c02af_th.png"}';
        // $params = '{"FileUrl":"https://bkimg.cdn.bcebos.com/pic/a08b87d6277f9e2f19b9d9b51730e924b999f3fb?x-bce-process=image/watermark,image_d2F0ZXIvYmFpa2U4MA==,g_7,xp_5,yp_5"}';
        // $params = '{"FileUrl":"https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2831692214,4267728091&fm=26&gp=0.jpg"}'; // 暴恐
        // $params = '{"FileUrl":"http://images.china.cn/attachement/jpg/site1000/20160712/7427ea2109f818eea0f319.jpg"}';
        // $params = '{"FileUrl":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595330981900&di=59b58735a3ef333b9232b00ecd9fefe0&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn06%2F360%2Fw1200h760%2F20180810%2F4101-hhnunsq4366079.jpg"}';
        // $params = '{"FileUrl":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595391514971&di=28c8a75e652002a0a0d1a923e73bbc07&imgtype=0&src=http%3A%2F%2Fupload.sanqin.com%2F2016%2F0721%2F1469082434701.jpg%3Fsize%3D600x324"}';
        $res = \think\Hook::listen('image_moderation', $params);
        // halt($res);
        if ($res[0]['Data']['EvilFlag'] > 0 || $res[0]['Data']['EvilType'] > 100) {
            $result = false;
            function checkResult($labels,$score,$typeText){
                $preposition = '图片审核不通过，恶意类型：';
                if( $labels !== '' ){
                    $labelsCount = count($labels);
                    $label = '';
                    for ($i=0; $i <= ($labelsCount-1); $i++) {
                        if($labelsCount > 1){
                            if( ($labelsCount-1) == $i){
                                $label .= $labels[$i];
                            }else{
                                $label .= $labels[$i] . '、';
                            }
                        }else{
                            $label .= $labels[$i];
                        }
                    }
                }else{
                    $labels = '';
                }
                return $preposition . $typeText . '；' . '标签：' . $label . '；' . '分值：' . $score;
            }
            switch ($res[0]['Data']['EvilType'])
            {
                case "20001":
                    $faceNames = $res[0]['Data']['PolityDetect']['FaceNames'];
                    $score = $res[0]['Data']['PolityDetect']['Score'];
                    $data = checkResult($faceNames,$score,'政治');
                    break;
                case "20002":
                    $labels = $res[0]['Data']['PornDetect']['Labels'];
                    $score = $res[0]['Data']['PornDetect']['Score'];
                    $data = checkResult($labels,$score,'色情');
                    break;
                case "20006":
                    $labels = $res[0]['Data']['IllegalDetect']['Labels'];
                    $score = $res[0]['Data']['IllegalDetect']['Score'];
                    $data = checkResult($labels,$score,'涉毒违法');
                    break;
                case "20007":
                    $data = '图片审核不通过,恶意类型：谩骂';
                    break;
                case "20103":
                    $labels = $res[0]['Data']['HotDetect']['Labels'];
                    $score = $res[0]['Data']['HotDetect']['Score'];
                    $data = checkResult($labels,$score,'性感');
                    break;
                case "24001":
                    $labels = $res[0]['Data']['TerrorDetect']['Labels'];
                    $score = $res[0]['Data']['TerrorDetect']['Score'];
                    $data = checkResult($labels,$score,'暴恐');
                    break;
                default:
                    $data = '图片审核不通过';
            }
            die($data);
        } else {
            die('ok');
        }
    }

}
